package com.gxljc.bear.crawler.itaogao.jingji21;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gxljc.commons.mongo.cli.BaseMongoRepository;
import com.gxljc.bear.crawler.base.DolphinCrawlerConsts;
import com.gxljc.bear.crawler.base.DolphinFetchData;
import com.gxljc.bear.crawler.itaogao.ItaogaoConst;
import com.gxljc.bear.crawler.itaogao.NewsPageTable;
import com.gxljc.bear.crawler.itaogao.NewsPageTemplate;
import com.gxljc.bear.crawler.itaogao.util.MongodbUtil;
import com.gxljc.bear.crawler.proxy.ProxyUtil;
import com.gxljc.bear.crawler.util.DateUtil;
import com.gxljc.bear.crawler.util.HtmlUtil;
import com.gxljc.bear.crawler.util.MD5Util;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.io.Serializable;
import java.util.*;

/**
 * 21世纪经济报道 seed 数据爬虫。
 *
 * @author tanghaitao
 * @since 2022-9-6
 */
public class Jingji21UpdateCrawler implements Serializable {
    public static Logger LOG = Logger.getLogger(Jingji21UpdateCrawler.class);
    private Boolean proxy = false;

    public Jingji21UpdateCrawler(Boolean proxy) {
        this.proxy = proxy;
    }

    public void crawl() throws Exception {
        ProxyUtil.initQueue(proxy);
        String seeds = getSeed();
        crawl(seeds);
    }

    //单条url入口
    public int crawl(String url) throws Exception {
        LOG.info("crawl url = " + url);
        DolphinFetchData fetchData = DolphinFetchData.getInstance(DolphinCrawlerConsts.CrawlerChannelType.bear.getName());
        String result = fetchData.getResult(url, proxy, ItaogaoConst.CRAWL_TIMEOUT);
        if (StringUtils.isEmpty(result)) {
            LOG.error("page result is empty url = " + url);
            return DolphinCrawlerConsts.RESULT_NO;
        }
        List<NewsPageTable> tables = extract(result,url);
        MongodbUtil.saveMongodb(tables,ItaogaoConst.MONGODB_TABLE.JINGJI21.getValue());
        return DolphinCrawlerConsts.RESULT_YES;
    }

    private List<NewsPageTable> extract(String result, String url) throws Exception {
        final Gson GSON = new Gson();
        NewsPageTemplate template = GSON.fromJson(result, new TypeToken<NewsPageTemplate>() {
        }.getType());
        if (template == null) return null;
        return parseObject(template,url);
    }

    private List<NewsPageTable> parseObject(NewsPageTemplate template, String url) throws Exception{
        List<NewsPageTable> tables = new LinkedList<>();
        List<String> crawlUrls = template.getCrawlUrl();
        List<String> titles = template.getTitle();
        if(CollectionUtils.isEmpty(crawlUrls)) return null;
        int size = crawlUrls.size();
        if(size!=titles.size()){
            throw new Exception("url size not equal title size");
        }
        for(int i = 0;i<size;i++){
            String crawlUrl = crawlUrls.get(i);
            String title = titles.get(i);
            if(StringUtils.isEmpty(title)) continue;
            if(title.equals("广告")) continue;   //过滤广告
            if(title.equals("无标题")) continue;   //过滤无标题
            NewsPageTable table = new NewsPageTable();
            table.setId(genId(crawlUrl));
//            table.setCrawlFlag(0);
            table.setCrawlUrl(HtmlUtil.pictureUrlPref(crawlUrl,url));
            table.setTitle(title.replace("\n"," "));
            tables.add(table);
        }
        return tables;
    }

    //生成id
    private String genId(String href) {
        return  MD5Util.getMd5(href);
    }

    //构造URL seed
    public String getSeed() throws Exception {
        Date dateSeed = getDateSeed();
        String dateFormat = DateUtil.dateFormat(dateSeed, "yyyy-MM/dd");
        return String.format(ItaogaoConst.NEWSPAPER_SEED.JINGJI21.getValue(), dateFormat);
    }

    //获取从当前到1月1号的列表
    private Date getDateSeed() {
        Calendar now = Calendar.getInstance();
        return now.getTime();
    }
}
